<!--
 * @Author: wanglidong
 * @Date: 2021-05-24 11:16:11
 * @LastEditTime: 2022-03-24 19:04:55
 * @LastEditors: wanglidong
 * @Description:
 * @FilePath: \lowcode-front\src\views\frontProject\approveItem\tab-view-group\item\item-detail\item-problem-detail.vue
 * @nbsg
-->
<template>
  <div>
    <el-dialog width="60%" class="WholeScroll" :visible.sync="formShow" @close="handleClickDeal('cancel')" v-dialog-drag :modal-append-to-body="false" :close-on-click-modal="false">
      <span slot="title">
        <i class="iconfont icon-liuchengguanli-2"></i>
        <span>{{ title }}</span>
      </span>
      <div class="WholeScroll" style="max-height: 600px; overflow: auto;padding: 0 15px;">
        <el-form :model="formBaseData" ref="formBaseData" :rules="formBaseRules">
          <el-tabs v-model="activeName">
            <el-tab-pane label="基本信息" name="first">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="所在周" prop="orderDate" :label-width="formlabelWidth">
                    <el-date-picker style="width: 100%" v-model="formBaseData.week" type="week" @change="setWeekNum" format="yyyy 第 WW 周" placeholder="选择周" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    ">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="问题类型" prop="problemType" :label-width="formlabelWidth">
                    <el-select style="width: 100%" v-model="formBaseData.problemType" filterable placeholder="" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    " @change="">
                      <el-option v-for="(item, i) in selectList.problemType" :key="i" :label="item.name" :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="主办部门" prop="hostDepartment" :label-width="formlabelWidth">
                    <el-input v-model="formBaseData.hostDepartment" placeholder="主办部门" :disabled="detailType === 'check' || detailType === 'approve'"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="涉及单位" prop="unitsInvolved" :label-width="formlabelWidth">
                    <el-input v-model="formBaseData.unitsInvolved" placeholder="涉及单位" :disabled="detailType === 'check' || detailType === 'approve'"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item prop="problem" label="存在问题及影响事件" :label-width="formlabelWidth">
                    <el-input class="fill" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入存在问题及影响事件" v-model="formBaseData.problem" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    ">
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item prop="solution" label="下阶段建议解决方案" :label-width="formlabelWidth">
                    <el-input class="fill" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入下阶段建议解决方案" v-model="formBaseData.solution" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    ">
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="问题状态" prop="problemStatus" :label-width="formlabelWidth">
                    <el-select style="width: 100%" v-model="formBaseData.problemStatus" filterable placeholder="" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    " @change="">
                      <el-option v-for="(item, i) in selectList.status" :key="i" :label="item.name" :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if='formBaseData.problemStatus == 2'>
                  <el-form-item label="计划办结时间" prop="planDate" :label-width="formlabelWidth">
                    <el-date-picker style="width: 100%" v-model="formBaseData.planDate" type="date" format="yyyy-MM-dd" value-format='yyyy-MM-dd' placeholder="选择计划办结时间" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    ">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item prop="ifCoordinate" label="是否需要协调" :label-width="formlabelWidth">
                    <el-radio-group v-model="formBaseData.ifCoordinate" size="small" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    ">
                      <el-radio label="1">是</el-radio>
                      <el-radio label="2">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="formBaseData.ifCoordinate == '1'">
                <el-col :span="24">
                  <el-form-item prop="coordinateType" label="" :label-width="formlabelWidth">
                    <el-radio-group v-model="formBaseData.coordinateType" size="small" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    ">
                      <el-radio label="aa">需公司协调</el-radio>
                      <el-radio label="bb">需集团协调</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="formBaseData.ifCoordinate == '1'">
                <el-col :span="24">
                  <el-form-item prop="result" label="协调（处理）结果" :label-width="formlabelWidth">
                    <el-input class="fill" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入协调（处理）结果" v-model="formBaseData.result" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    ">
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="附件上传" prop="fileList" :label-width="formlabelWidth">
                    <cmsUploadFile ref="fileOne" :detail-id="detailId" :fileSystem="fileSystem['one']" :disabled="detailType === 'check'|| detailType === 'audit'" type="mul" info="支持上传 png/jpg/gif/doc/xlsx/ppt/pdf 文件" :detail-type="detailType" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>

            <el-tab-pane label="审批记录" name="second" v-if="
                formBaseData &&
                formBaseData.logList &&
                formBaseData.logList.length > 1
              ">
              <el-steps direction="vertical" :active="99">
                <el-step v-for="(item, i) in formBaseData.logList" :key="i">
                  <span slot="icon">{{ formBaseData.logList.length - i }}</span>
                  <div class="step_wrap" slot="title">
                    <div>
                      <span class="flag" :style="{
                          color:
                            item.taskDefKey === 'branch'
                              ? 'grey'
                              : !item.createTime && !item.taskDefKey
                              ? 'red'
                              : '#009be2',
                        }">【{{ item.operName }}】</span>
                      <span class="name" :style="{
                          color:
                            !item.createTime && !item.taskDefKey
                              ? 'red'
                              : '#009be2',
                        }">{{ item.createrName }}</span>
                      <span class="date">{{ item.createTime }}</span>
                    </div>
                    <div class="content">{{ item.description }}</div>
                  </div>
                </el-step>
              </el-steps>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <!--api操作按钮 除去上报-->
        <!--新建和编辑的暂存上报-->

        <template v-if="detailType === 'build' || detailType === 'edit'">
          <el-button size="small" type="primary" :loading="isLoading" @click="handleClickDeal('submit', { flag: 1 })"><i class="iconfont icon-icon_save"></i> 确 定
          </el-button>
        </template>
        <el-button size="small" @click="handleClickDeal('cancel')"><i class="iconfont icon-icon_cancel"></i> 取 消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Moment from 'moment'
const urlBussBase = 'contractapply'
import { getDept, getOneForProblem, submitApprovalProblem, resubmitApprovalProblem } from '@/api/buss/frontProject'
export default {
  // name: 'checknotice-manage-detail',
  name: urlBussBase + '-manage-detail',
  components: {
    //  审核用
    // audit_component: require("../../../../../components/audit/audit").default
  },
  props: {
    postDetail: {
      type: Object,
      default: {
        show: false,
        type: 'build',
        params: {},
      },
    },
  },
  watch: {
    postDetail(value) {
      console.log(value)
      // 显示详情弹窗
      this.formShow = value.show
      // 初始化窗口参数
      this.activeName = 'first'
      // 详情类型
      this.detailType = value.type
      // 详情的流程操作处理

      this.formBaseData.companyId = value.companyId
      this.formBaseData.projectId = value.projectId
      this.formBaseData.approvalType = value.approvalType

      this.detailActions.splice(0, this.detailActions.length)
      // 详情id
      this.baseDetailId = value.params === undefined ? '0' : value.params.detailId


      let approvalName = value.approvalName
      if (!approvalName) {
        approvalName = ''
      }
      if (this.detailType !== 'build') {
        // 获取详情请求
        this.getDetail()
      }
      if (this.detailType === 'build') {
        this.title = '新增' + approvalName + '问题登记'
        // this.getDept()
      }
      if (this.detailType === 'check') {
        this.title = '查看' + approvalName + '问题登记'
      }
      if (this.detailType === 'edit') {
        this.title = '修改' + approvalName + '问题登记'
      }
    },
  },
  data() {
    return {
      fileList: [],
      urlBussBase: 'contractapply',
      newDetName: '',
      isLoading: false,
      detailType: 'build', // 详情类型 build新建 check不可编辑查看 edit编辑
      detailId: '', // 当前详情的id
      baseDetailId: '', // 当前详情的id
      detailActions: [], // 当前详情的操作项
      formShow: false, // 表单展示
      formlabelWidth: '150px', // 表单左侧标题宽度
      title: '问题登记',
      activeName: 'first',
      // 所有下拉框列表的集合
      selectList: {
        status: [
          {
            name: '已办结',
            id: '1'
          },
          {
            name: '未办结',
            id: '2'
          }
        ],
        problemType: [{
          name: '前期问题',
          id: '前期问题'
        },],
        department: [],
      },
      // 表单基本信息内容
      formBaseData: {
        week: '',
        postWeek: '',
        problemType: '',
        department: '',
        unit: '',
        problem: '',
        advise: '',
        problemStatus: '',
        deadLineDate: '',
        result: '',
        companyId: '',
        projectId: '',
        hostDepartment: '',
        unitsInvolved: '',
        solution: '',
        planDate: '',
        ifCoordinate: '2',
        coordinateType: '',
        approvalType: '',
      },
      // 表单基本信息验证
      formBaseRules: {
        unitsInvolved: [
          { required: true, message: '请输入' + '涉及单位', trigger: 'blur' },
        ],
        problem: [
          { required: true, message: '请输入' + '存在问题及影响事件', trigger: 'blur' },
        ],
        money: [
          { required: true, message: '请输入' + '批复金额', trigger: 'blur' },
        ],
        week: [
          { required: true, message: '请选择' + '周', trigger: 'change' },
        ],
        // problemType: [
        //   { required: true, message: '请选择' + '问题类型', trigger: 'change' },
        // ],
        problemStatus: [
          { required: true, message: '请选择' + '问题状态', trigger: 'change' },
        ],
        isNeedXT: [
          { required: true, message: '请选择' + '是否需要协调', trigger: 'change' },
        ],
        planDate: [
          { required: true, message: '请选择' + '计划办结日期', trigger: 'change' },
        ],
      },
      //  是否需要出现标段
      fileSystem: {
        'one': {
          sys: 'buss',
          module: 'approvalProblem',
          part: 'one',
          compoName: 'fileOne'
        }
      },
    }
  },

  filters: {
    moneyFilter(value) {
      try {
        let before = value.toFixed(2)
        before = before.toString()
        let num = before.split('.')[0]
        let numSmall = before.split('.')[1]
        let result = [],
          counter = 0
        num = (num || 0).toString().split('')
        for (let i = num.length - 1; i >= 0; i--) {
          counter++
          result.unshift(num[i])
          if (!(counter % 3) && i != 0) {
            result.unshift(',')
          }
        }
        let after =
          numSmall === undefined
            ? result.join('')
            : result.join('') + '.' + numSmall
        return after
      } catch (e) {
        return ''
      }
    },
  },
  created() {

  },
  methods: {
    /**
     * 加载文件
     **/
    loadFiles() {
      this.$nextTick(() => {
        for (let k in this.fileSystem) {
          let fileProp = this.fileSystem[k]
          this.$refs[fileProp.compoName].init()
        }
      })

    },
    /**
     * 保存文件
     */
    saveFiles() {
      for (let k in this.fileSystem) {
        let fileProp = this.fileSystem[k]
        this.$refs[fileProp.compoName].saveAll(this.detailId)
      }
    },
    setWeekNum() {
      //注意，当返回值是中国标准时间的格式时使用moment.js的时候一定要加上.utcOffset(480)，用来转换时区
      if (this.formBaseData.week) {
        this.formBaseData.postWeek = Moment(this.formBaseData.week).utcOffset(480).format("YYYY第WW周")
      } else {
        this.formBaseData.postWeek = ''
      }
    },
    getDept() { //获取部门列表
      getDept(this.formBaseData.projectId).then((res) => {
        let data = res.list
        // 表单信息
        this.selectList.department = JSON.parse(JSON.stringify(data))
      })
        .catch((res) => {
          console.log('请求出现错误', res)

        })
    },
    changeFileOne(file) {
      this.$set(this, 'fileList', [...file])
    },
    moneyFilter(value) {
      try {
        let before = value.toFixed(2)
        before = before.toString()
        let num = before.split('.')[0]
        let numSmall = before.split('.')[1]
        let result = [],
          counter = 0
        num = (num || 0).toString().split('')
        for (let i = num.length - 1; i >= 0; i--) {
          counter++
          result.unshift(num[i])
          if (!(counter % 3) && i != 0) {
            result.unshift(',')
          }
        }
        let after =
          numSmall === undefined
            ? result.join('')
            : result.join('') + '.' + numSmall
        return after
      } catch (e) {
        return ''
      }
    },
    // 获取详情请求 api
    getDetail() {
      getOneForProblem(this.baseDetailId).then((res) => {
        if (res.code === 200) {
          let data = res.data
          // 表单信息
          this.formBaseData = JSON.parse(JSON.stringify(data))
          this.detailId = this.formBaseData.id
          // this.getDept()
          this.loadFiles()
          // 文件系统
          // this.$refs.cmsFileTables.getFiles()
        } else {
          // this.$messageError(res.data.message)
          console.log('请求出现错误', res)
        }
      })
        .catch((res) => {
          console.log('请求出现错误', res)
          // this.$messageError(this.$route.name + '获取详情请求-请求失败')
        })
    },
    // 提交详情 提交1/暂存0 新建0/修改1
    submitDetail(type, callback) {
      if (this.detailType === 'build') {
        this.formBaseData.id = this.detailId
        submitApprovalProblem(this.formBaseData).then((res) => {
          if (res.code === 200) {
            this.detailId = res.data.id
            this.isLoading = false
            if (callback) callback()
          } else {
            this.isLoading = false
          }
        }).catch((res) => {
          console.log('请求出现错误', res)
          this.isLoading = false
        })
      } else {
        this.formBaseData.id = this.detailId
        resubmitApprovalProblem(this.formBaseData).then((res) => {
          if (res.code === 200) {
            this.isLoading = false
            if (callback) callback()
          } else {
            this.isLoading = false
          }
        }).catch((res) => {
          console.log('请求出现错误', res)
          this.isLoading = false
        })
      }
    },
    // 事件处理的api请求
    sealDealHttp(url, query, params, callback) {
      this.$httpPost(this.$store.state.httpHost.buss + url + query, params)
        .then((res) => {
          if (res.data.status === 1) {
            if (callback) callback(res.data)
          } else {
            this.$messageError(res.data.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          console.log(res)
        })
    },
    // 点击各个流程的按钮事件
    handleClickDeal(type, res) {
      console.log(type, res)
      switch (type) {
        // 取消，关闭窗口
        case 'cancel':
          // 重置表单验证
          this.$refs['formBaseData'].resetFields()
          // 清空表单内容
          this.formBaseData = {
            week: '',
            postWeek: '',
            problemType: '',
            department: '',
            unit: '',
            problem: '',
            advise: '',
            problemStatus: '',
            deadLineDate: '',
            needWhich: 'aa',
            result: '',
            companyId: '',
            projectId: '',
            hostDepartment: '',
            unitsInvolved: '',
            solution: '',
            planDate: '',
            ifCoordinate: '2',
            coordinateType: '',
            approvalType: '',
          } // 表单基本信息内容
          // 清空文件
          this.selectList.file = []
          for (let k in this.fileSystem) {
            let fileProp = this.fileSystem[k]
            this.$refs[fileProp.compoName].cancelAll()
          }
          // 关闭弹窗
          this.formShow = false
          this.enableSectionSelection = false
          break
        // 保存
        case 'submit':
          let flag = res.flag
          // 表单验证
          this.$refs['formBaseData'].validate((valid) => {
            if (valid) {
              // 再验证其他内容
              // 整理文件信息
              this.isLoading = true
              // 提交详情
              this.submitDetail(flag, () => {
                // 绑定文件到表单
                this.saveFiles()
                // this.$refs.cmsFileTables.bindAllFile(this.detailId)
                this.formShow = false
                this.isLoading = false
                // 传值给父组件刷新列表
                this.$emit('reloadList')
              })
            } else {
              this.isLoading = false
            }
          })
          break
        // 删除
        case 'delete':
          this.$prompt('删除理由', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          })
            .then(({ value }) => {
              if (value === null || value === '') {
                this.$messageError('请填写删除理由后重试')
                return
              }
              this.sealDealHttp(
                res.url,
                ``,
                {
                  id: this.detailId,
                  description: value,
                },
                () => {
                  this.$messageSuccess('删除成功!')
                  this.formShow = false
                  // 传值给父组件刷新列表
                  this.$emit('reloadList')
                }
              )
            })
            .catch(() => {
              console.log('请求出现错误')
            })
          break
      }
    },
    tableChange(val) {
      this.$set(this, 'buildUnitTable', [...val])
    },
    tableChange_htqd(val) {
      this.$set(this, 'buildUnitTable_htqd', [...val])
    },
  },
}
</script>

<style scoped lang="scss">
.el-select.half {
  width: 250px;
}

.el-select.fill {
  width: 800px;
}

.contract_input {
  width: 250px;
}

.contract_input2 {
  width: 240px;
}

.el-input .el-select {
  width: 130px;
}

.fee_add {
  color: #008fe0;
  border-color: #008fe0;
  float: right;
  margin-bottom: 10px;
}
</style>
